package com.moonspring.dao;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;

import net.sf.json.JSONObject;

import org.bson.Document;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.moonspring.db.mongodb;
import com.moonspring.model.WebLogModel;
import com.moonspring.util.Contans;

public class WebLogDao {
	//添加访问日志
	public int addWebLog(WebLogModel wlm){
		int r = -1;
		mongodb mym = null;
		try {
			long time = System.currentTimeMillis();
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String ftime = dateFormat.format(time);
			Document webLog = new Document("os",wlm.getOs());
			webLog.put("browser", wlm.getBrowser());
			webLog.put("fip", wlm.getIp());
			webLog.put("realip", wlm.getRealIp());
			webLog.put("uri", wlm.getUri());
			webLog.put("url", wlm.getUrl());
			webLog.put("pattam", wlm.getPattam());
			webLog.put("time", ftime);
			webLog.put("type", wlm.getType());
			mym = new mongodb(Contans.DBHOST, Contans.DBPORT);
			MongoDatabase db = mym.getConnection(Contans.DBNAME);
			MongoCollection<Document> dc = db.getCollection(Contans.WEBLOGTABLE);
			dc.insertOne(webLog);
			r = 1;
		} catch (Exception e) {
			e.printStackTrace();
			r = -1;
		} finally {
			if(mym != null){
				mym.close();
			}
		}
		return r;
	}
	
	//读取访问日志列表
	@SuppressWarnings("unchecked")
	public String listWebLog(JSONObject query){
		ArrayList<String> res = new ArrayList<String>();
		mongodb mym = null;
		JSONObject r = new JSONObject();
		long total = -1;
		try {
			Iterator<String> keys = query.keys();
			Document filter = new Document();
			while (keys.hasNext()) {
				String key = keys.next();
				filter.put(key, query.get(key));
			}
			mym = new mongodb(Contans.DBHOST, Contans.DBPORT);
			MongoDatabase db = mym.getConnection(Contans.DBNAME);
			MongoCollection<Document> dc = db.getCollection(Contans.WEBLOGTABLE);
			FindIterable<Document> weblogi = dc.find(filter).sort(new Document("_id",-1));
			MongoCursor<Document> weblogc = weblogi.iterator();
			while(weblogc.hasNext()){
				try {
					Document j = weblogc.next();
					JSONObject weblog = JSONObject.fromObject(j.toJson());
					weblog.put("_id", j.get("_id"));
					res.add(weblog.toString());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			total = dc.count(filter);
		} catch (Exception e) {
			e.printStackTrace();
			total = -1;
		} finally {
			if(mym != null){
				mym.close();
			}
			r.put("total", total);
			r.put("res", res.toString());
		}
		return r.toString();
	}
}
